var windowName = "index";
var Page,map,listService,listShop,listTask;
apiready = function () {
    map = api.require('bMap');
    TopicList = new List();
    Page = createVM("#Page", {
        //页面数据
        banner: [
            {pic:picBanner,action:""}
        ]
        , vScrollH: 0
        ,statistic:{}
        ,cats:[]
        ,cat10:[]
        ,citys:[]
        ,cityName:""
        ,news:[{
            title:"数据获取中……"
            ,intro:"数据获取中……"
            ,pic:picBanner
        }]
        ,gpsOpen:false
        ,showScroll:false

        //底部列表数据
        , active: 0
        , curTab: 0
        ,listLoading:false
        ,serviceList:[]
        ,shopList:[]
        ,taskList:[]
        ,productCats:[]
        ,announce:[]
        ,product:[]
    }, {
        //页面方法
        "init": function () {

            // 先检查权限
            var resultList = api.hasPermission({
                list:['camera','photos','location','storage']
            });
            var resultNameCn = {
                camera:'我们将使用相机权限，用于任务发布时或信息提交时的图片提交，禁用后将导致程序错误。'
                ,photos:'我们将使用相册权限，用于任务发布时或信息提交时的图片提交，禁用后将导致程序错误。'
                ,location:'我们将使用位置权限，提供基于附近位置的任务发布和接取功能，禁用后将导致程序错误。'
                ,phone:'我们将使用拨号权限,提供更便捷的联系商家服务，使用拨号权限后您仍然需要手动拨打电话的操作。'
                ,storage:'我们将使用存储权限，用于存储缓存数据，以提供更流畅的服务。'
            }
            // console.log()
            // logJson("112233")
            // logJson(resultList)
            resultList.map(function (data) {
                if (data.granted === false) {
                    showConfirm( resultNameCn[data.name],function () {
                        api.requestPermission({
                            list:[data.name],
                            code:1
                        }, function(ret, err){

                        });
                    },function () {

                    })
                }

            })


            var banner = getLocData("bannerIndex")
            if (isTrue(banner)) {
                this.banner = banner
            }
            this.news = [{
                title:"数据获取中……"
                ,intro:"数据获取中……"
                ,pic:picBanner
            }];
            var wh = eleWidthAndHeight("#newsLine");
            this.vScrollH = wh.h
            //检查配置参数
            var cityName = getLocData("city");
            if (isTrue(cityName)) {
                Page.cityName = cityName;
            }
            getIndexDataAndCheckConfig()
            getLocation();
        }
        , "OnPullUpLoadMore": function () {
            // startPullUpLoadMore();
            // TopicList.getList()
        }
        , search: function () {
            setOpenAnimFromBottom()
            goto("search")
        }
        ,tab:function (index) {
            log(index)
            // Page.listLoading = true;
            // setTimeout(function () {
            //     Page.listLoading = false;
            // },3000)
        }

        ,gotoCat:function (id) {
            var parentIndex = 0;
            var sonIndex = 0;
            logJson(id)
            logJson(Page.cats)
            Page.cats.map(function (data,parentIndex) {
                if (data.id == id) {
                    goto('services',{cat1:parentIndex,cat2:-1})
                }
            })
        }
        ,tabTo:function (index) {
            api.execScript({
                name: 'root',
                script: "tabTo("+index+")"
            });
        }
    })
    Page.init();
    onPullUpLoadMore(function () {
        clearLoading();
        if (Page.curTab === 0){
            listService.getList();
        }
        if (Page.curTab === 1){
            listShop.getList();
        }
        if (Page.curTab === 2){
            listTask.getList();
        }
    })
    onScrollDown(function () {

    },1000)


}

function updateWinData() {
    //首页返回后重新设置缓存的地区信息
    var cityName = getLocData("city");
    if (isTrue(cityName)) {
        Page.cityName = cityName;
    }
    listTask.reload()
    listShop.reload()
    listService.reload()
    getIndexDataAndCheckConfig();
}

function getIndexDataAndCheckConfig() {
    var cats = getLocData("cacheCats");if (isTrue(cats)){Page.cats = cats;}
    var citys = getLocData("citys");if (isTrue(citys)){Page.citys = citys;}
    formatCats()
    apiGet("/app/config", {}, function (res) {
        var cats = res.data.cats;
        Page.cats = cats;
        formatCats()
        setLocData("cacheCats",cats);
        var conf = res.data.conf;
        setLocData("conf",conf);
        var citys = res.data.citys;//TODO 这里好像没有走网络数据，城市的数据在js文件里面
        setLocData("citys",citys);
        //首页banner
        var bannerIndex  = res.data.bannerIndex;
        Page.banner = bannerIndex;
        if (isTrue(bannerIndex)) {setLocData("bannerIndex",bannerIndex);}
        //需求大厅banner
        var bannerTask  = res.data.bannerTask;
        if (isTrue(bannerTask)) {setLocData("bannerTask",bannerTask);}
        //接单banner
        var bannerMatch  = res.data.bannerMatch;
        if (isTrue(bannerMatch)) {setLocData("bannerMatch",bannerMatch);}
        //平台综合数据
        var statistic = res.data.statistic;
        setLocData("statistic",statistic);
        Page.statistic = statistic;
    });
    var news = getLocData("news");if (isTrue(news))Page.news = news;
    apiGet("/api/articles",{cat:3,limit:3},function (res,code) {
        if (code == 200) {
            Page.news = res.data;
            setLocData("news",Page.news);
        }
    })
    var productCats = getLocData("productCats");if (isTrue(productCats))Page.productCats = productCats;
    apiGet("/app/index",{},function (res,code) {
        logJson(res,"appIndex_")
        if (code == 200) {
            Page.productCats = res.data;
            setLocData("productCats",Page.productCats);
        }
    })
    var announce = getLocData("announce");if (isTrue(announce))Page.announce = announce;
    logJson(announce,"test_announce")
    apiGet("/app/announce",{event:[1,4]},function (res,code) {
        logJson(res,"announce_")
        if (code == 200) {
            Page.announce = res.data;
            setLocData("announce",Page.announce);
        }
    })
    var product = getLocData("product");if (isTrue(product))Page.product = product;
    logJson(product,"test_product")
    apiGet("/app/recomment",{event:[1,4]},function (res,code) {
        logJson(res,"recomment")
        if (code == 200) {
            Page.product = res.data;
            setLocData("product",Page.product);
        }
    })

}
function formatCats() {
    if (isTrue(Page.cats)) {
        var countCat = Math.ceil(Page.cats.length/10);
        var cats10 = new Array();
        for (var i=0 ;i<countCat;i++) {
            cats10[i] = []
            for (var index in Page.cats) {
                var data = Page.cats[index]
                if (i*10<=index && index < (i+1)*10) {
                    cats10[i].push(data)
                }
            }
        }
        Page.cat10 = cats10;
    }
}

function getLocation() {
    var count = 0;
    map.getLocation({
        accuracy: '100m',
        autoStop: false,
        filter: 1
    }, function(ret, err) {
        logJson(ret,"Map getLocation")
        if (ret.status) {
            Page.gpsOpen = false;
            setLocData("lat",ret.lat)
            setLocData("lon",ret.lon)
            map.stopLocation()
            logJson(ret,"gpsLocation");
            getBottomData()
        } else {
            Page.gpsOpen = true;
            count ++
            if (
                count === 5
                || count === 10
                || count === 20
                || count === 30
                || count === 50
                || count === 100
            ) {
                var myCity = new BMap.LocalCity();
                myCity.get(function (res) {
                    logJson(res,"LocalCity")
                    setLocData("lat",res.center.lat)
                    setLocData("lon",res.center.lng)
                    getBottomData()
                });
            }
        }
    });
}


function getBottomData() {
    //下方列表数据
    var lat = getLocData("lat");
    var lon = getLocData("lon");
    //--精选服务
    listService = new List()
    listService.setData({lat:lat,lon:lon}).setUrl("/app/product/list").setCbFunc(function (res) {
        clearLoading()
        logJson(res,"listService_")
        Page.serviceList = res
    }).getList();
    //--附近商家
    listShop = new List()
    listShop.setData({lat:lat,lon:lon}).setUrl("/app/shop/near").setCbFunc(function (res) {
        clearLoading()
        logJson(res,"listShop_")
        Page.shopList = res
    }).getList();
    //--最新需求
    listTask = new List()
    listTask.setData({
        lat:lat,
        lon:lon,
        distance:20,
        orderby:""
    }).setUrl("/api/task/get/all").setCbFunc(function (res) {
        logJson(res,"taskList_")
        clearLoading();
        Page.taskList = res
        // getDistance()
    }).getList();
}


$(function () {


})
